export class Request {
  constructor(io, opt) {
    this.io = io
    this._debug = false
    this.opt = {
      base: '',
      ...opt,
    }
  }

  handleServerErr(e) {}

  getRequestArgs(...args) {
    let fullPath = ''
    if (args.length < 2) {
      if (typeof args[0] === 'object' && args[0].hasOwnProperty('path')) {
        fullPath = this.opt.base + args[0].path
        return [
          fullPath,
          {
            ...args[0].params,
          },
        ]
      }
      fullPath = this.opt.base + args[0]
      return [
        fullPath,
        {},
      ]
    } else {
      if (typeof args[0] === 'string') {
        fullPath = this.opt.base + args[0]
        return [
          fullPath,
        ].concat(args.slice(1))
      }
      return args
    }
  }

  _request(method, ...args) {
    let self = this
    return new Promise((resolve, reject) => {
      let requestArgs = self.getRequestArgs(...args)
      if (self._debug) {
        console.log('requestArgs :', requestArgs)
      }
      self.io[method](...requestArgs).then(res => {
        resolve(res)
      }).catch(e => {
        console.error('handleServerErr', e)
        if (self.handleServerErr) {
          self.handleServerErr(e)
        }
      }).finally(() => {
        // console.log('_request finally')
        if (self.onFinally) {
          self.onFinally(self)
        }
      })
    })
  }

}
